/*
 *    Copyright (c) 2018-2025, nart All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: nart
 */
package com.nai365.nart.product.service.impl;

import cn.hutool.core.lang.Console;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nai365.nart.common.core.constant.SecurityConstants;
import com.nai365.nart.common.core.es.SkuEsModel;
import com.nai365.nart.common.core.util.R;
import com.nai365.nart.common.core.vo.WareSkuVo;
import com.nai365.nart.common.security.util.SecurityUtils;
import com.nai365.nart.member.entity.Member;
import com.nai365.nart.member.feign.RemoteMemberService;
import com.nai365.nart.product.constant.ProductStatusEnum;
import com.nai365.nart.product.entity.SkuInfo;
import com.nai365.nart.product.mapper.SkuInfoMapper;
import com.nai365.nart.product.service.SkuInfoService;
import com.nai365.nart.search.api.feign.SearchFeignService;
import com.nai365.nart.ware.api.feign.WareFeignService;
import lombok.AllArgsConstructor;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * sku信息
 *
 * @author baogs
 * @date 2022-07-01 11:05:45
 */
@Service
@AllArgsConstructor
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoMapper, SkuInfo> implements SkuInfoService {
	SearchFeignService searchFeignService;

	private final RemoteMemberService remoteMemberService;

	private final WareFeignService wareFeignService;

	@Override
	public R up(List<Long> skuIds, String price) {

		//1、查出当前spuId对应的所有sku信息,品牌的名字

//		ArrayList<SkuEsModel> spus = new ArrayList<>();
		List<SkuInfo> list1 = list(Wrappers.<SkuInfo>lambdaQuery().in(SkuInfo::getSkuId, skuIds));
		List<Long> ids = list1.parallelStream().map(item -> item.getOwnerId()).collect(Collectors.toList());


		R headerAndNickname = remoteMemberService.findHeaderAndNickname(ids, SecurityConstants.FROM_IN);
		JSONObject data = JSONUtil.parseObj(headerAndNickname.getData());


		List<SkuEsModel> spus = list1.parallelStream().map(item -> {
//			Boolean result = checkOwner(item);
//		if (!result){
//			return R.failed("只能操作自己的藏品");
//		}

//			if (item.getPublishStatus() == 1) {
//				return R.failed("商品寄售中");
//			}
			SkuEsModel spuEsModel = new SkuEsModel();
			Long ownerId = item.getOwnerId();
			JSONObject user = (JSONObject) data.get(ownerId + "");
			BeanUtils.copyProperties(item, spuEsModel);
			spuEsModel.setPrice(new BigDecimal(price));
			if (user != null) {
				Object header = user.get("header");
				spuEsModel.setHeader(header !=null?user.get("header").toString():"");
				spuEsModel.setNickname(user.get("nickname").toString());
			}
			return spuEsModel;

		}).collect(Collectors.toList());
//		SkuInfo byId = getById(skuId);


		//TODO 5、将数据发给es进行保存：nart-search
		R r = searchFeignService.productSkuUp(spus, SecurityConstants.FROM_IN);

		if (r.getCode() == 0) {
			//远程调用成功
			//TODO 6、修改当前spu的状态

			List<SkuInfo> collect = list1.parallelStream().map(item -> {
				SkuInfo skuInfo = new SkuInfo();
				skuInfo.setSkuId(item.getSkuId());
				skuInfo.setPublishStatus(1);
				return skuInfo;
			}).collect(Collectors.toList());

			boolean b = updateBatchById(collect);

			if (b) {

				List<WareSkuVo> wareSkuVos = list1.parallelStream().map(item -> {
					WareSkuVo wareSkuVo = new WareSkuVo();
					wareSkuVo.setSkuId(item.getSkuId());
					wareSkuVo.setSkuName(item.getSkuName());
					wareSkuVo.setOwnerId(item.getOwnerId());
					wareSkuVo.setStock(1);
					return wareSkuVo;
				}).collect(Collectors.toList());
				wareFeignService.saveWare(wareSkuVos, SecurityConstants.FROM_IN);
			}
			return R.ok(b,"上架成功");
		} else {
			//远程调用失败
			//TODO 7、重复调用？接口幂等性:重试机制
			return R.failed("上架失败");
		}
	}

	@Nullable
	private Boolean checkOwner(SkuInfo byId) {
		Long ownerId = byId.getOwnerId();
		Long id = SecurityUtils.getUser().getId();
		return ownerId == id;
	}

	@Override
	public boolean down(Long skuId) {
//		SkuInfo byId = getById(skuId);
//		Boolean result = checkOwner(byId);
//		if (!result) {
//			return false;
//		}
		SkuInfo spuInfo = new SkuInfo();
		spuInfo.setSkuId(skuId);
		spuInfo.setPublishStatus(0);

		return this.updateById(spuInfo);
	}

	@Override
	public List<SkuInfo> findMySkuBySpuIdAndStatus(Long spuId, Integer status) {
		LambdaQueryWrapper<SkuInfo> queryWrapper = Wrappers.lambdaQuery();
		queryWrapper.eq(SkuInfo::getPublishStatus, status)
				.eq(SkuInfo::getOwnerId, SecurityUtils.getUser().getId())
				.eq(SkuInfo::getSpuId, spuId);
		return this.list(queryWrapper);
	}

	/**
	 * 锁定一个可用的sku
	 *
	 * @param spuId spu id
	 * @return SkuInfo
	 */
	public SkuInfo lockSkuInfo(Long spuId) throws Exception {
		LambdaQueryWrapper<SkuInfo> queryWrapper = Wrappers.lambdaQuery();
		queryWrapper.eq(SkuInfo::getPublishStatus, 0)
				.eq(SkuInfo::getSpuId, spuId)
				.eq(SkuInfo::getOwnerId, 0);
		List<SkuInfo> skuInfoList = this.list(queryWrapper);
		if (skuInfoList == null || skuInfoList.size() <= 0) {
			throw new Exception("锁藏品失败,没有可用藏品");
		}
		SkuInfo skuInfo = skuInfoList.get(0);
		R<Member> remote = remoteMemberService.getById(SecurityUtils.getUser().getId());
		skuInfo.setPublishStatus(6);
		skuInfo.setOwnerId(SecurityUtils.getUser().getId());
		if (remote.getCode() == 0 && remote.getData() != null) {
			Member member = remote.getData();
			skuInfo.setOwnerAddress(member.getOpbChainClientAddress());
		}
		this.updateById(skuInfo);
		return skuInfo;
	}

	@Override
	public SkuInfo unLockSkuInfo(SkuInfo skuInfo) {
		skuInfo.setPublishStatus(0);
		skuInfo.setOwnerId(0L);
		skuInfo.setOwnerAddress("0xb96a0b55052c5d081eed749161b1dc2176b5a61f");
		this.updateById(skuInfo);
		return skuInfo;
	}

	@Override
	public SkuInfo findSkuInfoBySkuId(Long skuId) {
		LambdaQueryWrapper<SkuInfo> skuInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
		skuInfoLambdaQueryWrapper.eq(SkuInfo::getSkuId, skuId);
		return this.getOne(skuInfoLambdaQueryWrapper);
	}
}
